from PySide6 import QtCore, QtGui, QtWidgets

import os
import sys
import subprocess

from ui_mainwindow import Ui_MainWindow
import fire

from typing import List

class Commands:

    @staticmethod
    def ifconfig():
        return subprocess.check_output(['ifconfig']).decode()
    
    @staticmethod
    def route():
        return subprocess.check_output(['route']).decode()
    
    @staticmethod
    def ip_route():
        return subprocess.check_output(['ip', 'route']).decode()
    
    @staticmethod
    def ip_rule():
        return subprocess.check_output(['ip', 'rule']).decode()

class Worker(QtCore.QThread):
    Output = QtCore.Signal(list)
    
    def __init__(self, parent = ...):
        super().__init__(parent)

    def run(self):
        self.Output.emit([
            Commands.ifconfig(),
            Commands.route(),
            Commands.ip_rule(),
            Commands.ip_route(),
        ])

class NetworkAnalyzerWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)


        self.worker = Worker(self)
        self.worker.Output.connect(self.update_info)
        QtCore.QTimer.singleShot(1, self.worker.start)

    def update_info(self, output: List[str]):
        self.ui.text_ifconfig.setPlainText(output[0])
        self.ui.text_route.setPlainText(output[1])
        self.ui.text_ip_rule.setPlainText(output[2])
        self.ui.text_ip_route.setPlainText(output[3])


if __name__ == '__main__':

    if len(sys.argv) > 1:
        fire.Fire(Commands)
    else:
        app = QtWidgets.QApplication(sys.argv)
        widget = NetworkAnalyzerWindow()
        widget.setWindowTitle("Network Analyzer")
        widget.show()
        widget.move(QtGui.QGuiApplication.primaryScreen().availableGeometry().center() - widget.rect().center())
        sys.exit(app.exec())
